document.addEventListener('DOMContentLoaded', () => {
    // 获取画布和上下文
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');
    
    // 设置画布大小
    canvas.width = 400;
    canvas.height = 400;
    
    // 游戏参数
    const gridSize = 20; // 网格大小
    const tileCount = canvas.width / gridSize; // 网格数量
    
    // 难度设置
    const difficultySettings = {
        easy: {
            initialSpeed: 6,
            speedIncrement: 0.5,
            scorePerFood: 10,
            obstacleCount: 0,
            color: '#4CAF50'
        },
        medium: {
            initialSpeed: 8,
            speedIncrement: 0.8,
            scorePerFood: 15,
            obstacleCount: 5,
            color: '#FFA500'
        },
        hard: {
            initialSpeed: 10,
            speedIncrement: 1,
            scorePerFood: 20,
            obstacleCount: 10,
            color: '#FF4500'
        }
    };
    
    // 游戏变量
    let speed;
    let scorePerFood;
    let currentDifficulty;
    let obstacles = [];
    
    // 蛇的初始位置和大小
    let snake = [];
    let snakeLength = 3;
    
    // 蛇的初始位置和方向
    let headX = 10;
    let headY = 10;
    let velocityX = 0;
    let velocityY = 0;
    let nextVelocityX = 0;
    let nextVelocityY = 0;
    
    // 食物位置
    let foodX = 5;
    let foodY = 5;
    
    // 游戏状态
    let gameStarted = false;
    let gameOver = false;
    let score = 0;
    
    // 获取DOM元素
    const scoreElement = document.getElementById('scoreValue');
    const startButton = document.getElementById('startButton');
    const difficultySelect = document.getElementById('difficultySelect');
    const gameOverModal = document.getElementById('gameOverModal');
    const finalScoreElement = document.getElementById('finalScore');
    const playerNameInput = document.getElementById('playerName');
    const submitScoreButton = document.getElementById('submitScore');
    const playAgainButton = document.getElementById('playAgain');
    const leaderboardTabs = document.querySelectorAll('.leaderboard-tab');
    const leaderboardBody = document.getElementById('leaderboardBody');
    
    // 初始化排行榜
    initLeaderboard();
    
    // 初始化游戏
    function initGame() {
        // 获取当前选择的难度
        currentDifficulty = difficultySelect.value;
        
        // 设置难度相关参数
        speed = difficultySettings[currentDifficulty].initialSpeed;
        scorePerFood = difficultySettings[currentDifficulty].scorePerFood;
        
        // 重置游戏状态
        snake = [];
        snakeLength = 3;
        headX = 10;
        headY = 10;
        velocityX = 0;
        velocityY = 0;
        nextVelocityX = 0;
        nextVelocityY = 0;
        score = 0;
        gameOver = false;
        scoreElement.textContent = score;
        
        // 生成障碍物
        generateObstacles();
        
        // 生成食物
        generateFood();
    }
    
    // 生成障碍物
    function generateObstacles() {
        obstacles = [];
        const obstacleCount = difficultySettings[currentDifficulty].obstacleCount;
        
        for (let i = 0; i < obstacleCount; i++) {
            let obstacleX, obstacleY;
            let validPosition = false;
            
            // 确保障碍物不会生成在蛇的初始位置附近
            while (!validPosition) {
                obstacleX = Math.floor(Math.random() * tileCount);
                obstacleY = Math.floor(Math.random() * tileCount);
                
                // 检查是否与蛇的初始位置冲突
                const distanceFromSnake = Math.sqrt(
                    Math.pow(obstacleX - headX, 2) + 
                    Math.pow(obstacleY - headY, 2)
                );
                
                // 如果障碍物距离蛇头至少5个格子，则位置有效
                if (distanceFromSnake > 5) {
                    validPosition = true;
                    
                    // 检查是否与其他障碍物重叠
                    for (let j = 0; j < obstacles.length; j++) {
                        if (obstacleX === obstacles[j].x && obstacleY === obstacles[j].y) {
                            validPosition = false;
                            break;
                        }
                    }
                }
            }
            
            obstacles.push({ x: obstacleX, y: obstacleY });
        }
    }
    
    // 生成食物
    function generateFood() {
        // 随机生成食物位置
        function getRandomPosition() {
            return Math.floor(Math.random() * tileCount);
        }
        
        let validPosition = false;
        
        while (!validPosition) {
            foodX = getRandomPosition();
            foodY = getRandomPosition();
            validPosition = true;
            
            // 确保食物不会生成在蛇身上
            for (let i = 0; i < snake.length; i++) {
                if (snake[i].x === foodX && snake[i].y === foodY) {
                    validPosition = false;
                    break;
                }
            }
            
            // 确保食物不会生成在障碍物上
            if (validPosition) {
                for (let i = 0; i < obstacles.length; i++) {
                    if (obstacles[i].x === foodX && obstacles[i].y === foodY) {
                        validPosition = false;
                        break;
                    }
                }
            }
        }
    }
    
    // 游戏主循环
    function gameLoop() {
        if (gameStarted && !gameOver) {
            updateGame();
        }
        drawGame();
        
        // 根据游戏状态决定是否继续循环
        if (!gameOver) {
            setTimeout(gameLoop, 1000 / speed);
        } else {
            showGameOverModal();
        }
    }
    
    // 更新游戏状态
    function updateGame() {
        // 更新蛇的方向
        velocityX = nextVelocityX;
        velocityY = nextVelocityY;
        
        // 移动蛇头
        headX += velocityX;
        headY += velocityY;
        
        // 检查是否撞墙
        if (headX < 0 || headX >= tileCount || headY < 0 || headY >= tileCount) {
            gameOver = true;
            return;
        }
        
        // 检查是否撞到障碍物
        for (let i = 0; i < obstacles.length; i++) {
            if (headX === obstacles[i].x && headY === obstacles[i].y) {
                gameOver = true;
                return;
            }
        }
        
        // 检查是否吃到食物
        if (headX === foodX && headY === foodY) {
            snakeLength++;
            score += scorePerFood;
            scoreElement.textContent = score;
            generateFood();
            
            // 每得100分增加速度
            if (score % 100 === 0) {
                speed += difficultySettings[currentDifficulty].speedIncrement;
            }
        }
        
        // 更新蛇身
        snake.unshift({ x: headX, y: headY });
        
        // 保持蛇的长度
        while (snake.length > snakeLength) {
            snake.pop();
        }
        
        // 检查是否撞到自己
        for (let i = 1; i < snake.length; i++) {
            if (headX === snake[i].x && headY === snake[i].y) {
                gameOver = true;
                return;
            }
        }
    }
    
    // 绘制游戏
    function drawGame() {
        // 清空画布
        ctx.fillStyle = 'white';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        if (gameStarted) {
            // 绘制障碍物
            ctx.fillStyle = '#555';
            for (let i = 0; i < obstacles.length; i++) {
                ctx.fillRect(obstacles[i].x * gridSize, obstacles[i].y * gridSize, gridSize, gridSize);
            }
            
            // 绘制食物
            ctx.fillStyle = 'red';
            ctx.fillRect(foodX * gridSize, foodY * gridSize, gridSize, gridSize);
            
            // 绘制蛇
            const snakeColor = difficultySettings[currentDifficulty].color;
            for (let i = 0; i < snake.length; i++) {
                // 蛇头用深色，蛇身用浅色
                ctx.fillStyle = i === 0 ? snakeColor : lightenColor(snakeColor, 20);
                ctx.fillRect(snake[i].x * gridSize, snake[i].y * gridSize, gridSize, gridSize);
                
                // 绘制蛇身边框
                ctx.strokeStyle = 'black';
                ctx.strokeRect(snake[i].x * gridSize, snake[i].y * gridSize, gridSize, gridSize);
            }
            
            // 游戏结束显示
            if (gameOver) {
                ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                
                ctx.fillStyle = 'white';
                ctx.font = '30px Arial';
                ctx.textAlign = 'center';
                ctx.fillText('游戏结束!', canvas.width / 2, canvas.height / 2 - 20);
                ctx.fillText(`得分: ${score}`, canvas.width / 2, canvas.height / 2 + 20);
                
                startButton.textContent = '重新开始';
                gameStarted = false;
            }
        } else {
            // 游戏未开始时显示提示
            ctx.fillStyle = 'black';
            ctx.font = '20px Arial';
            ctx.textAlign = 'center';
            ctx.fillText('选择难度并点击"开始游戏"', canvas.width / 2, canvas.height / 2);
        }
    }
    
    // 显示游戏结束模态框
    function showGameOverModal() {
        finalScoreElement.textContent = score;
        gameOverModal.classList.add('show');
    }
    
    // 隐藏游戏结束模态框
    function hideGameOverModal() {
        gameOverModal.classList.remove('show');
        playerNameInput.value = '';
    }
    
    // 初始化排行榜
    function initLeaderboard() {
        // 确保每个难度都有排行榜数据
        const difficulties = ['easy', 'medium', 'hard'];
        
        difficulties.forEach(difficulty => {
            if (!localStorage.getItem(`leaderboard_${difficulty}`)) {
                localStorage.setItem(`leaderboard_${difficulty}`, JSON.stringify([]));
            }
        });
        
        // 默认显示简单难度的排行榜
        updateLeaderboardDisplay('easy');
        
        // 添加排行榜标签点击事件
        leaderboardTabs.forEach(tab => {
            tab.addEventListener('click', () => {
                // 移除所有标签的active类
                leaderboardTabs.forEach(t => t.classList.remove('active'));
                // 给当前点击的标签添加active类
                tab.classList.add('active');
                // 更新排行榜显示
                updateLeaderboardDisplay(tab.dataset.difficulty);
            });
        });
    }
    
    // 更新排行榜显示
    function updateLeaderboardDisplay(difficulty) {
        const leaderboardData = JSON.parse(localStorage.getItem(`leaderboard_${difficulty}`)) || [];
        
        // 清空排行榜
        leaderboardBody.innerHTML = '';
        
        // 添加排行榜数据
        leaderboardData.forEach((entry, index) => {
            const row = document.createElement('tr');
            
            const rankCell = document.createElement('td');
            rankCell.textContent = index + 1;
            
            const nameCell = document.createElement('td');
            nameCell.textContent = entry.name;
            
            const scoreCell = document.createElement('td');
            scoreCell.textContent = entry.score;
            
            row.appendChild(rankCell);
            row.appendChild(nameCell);
            row.appendChild(scoreCell);
            
            leaderboardBody.appendChild(row);
        });
        
        // 如果没有数据，显示提示
        if (leaderboardData.length === 0) {
            const row = document.createElement('tr');
            const cell = document.createElement('td');
            cell.colSpan = 3;
            cell.textContent = '暂无记录';
            cell.style.textAlign = 'center';
            row.appendChild(cell);
            leaderboardBody.appendChild(row);
        }
    }
    
    // 添加分数到排行榜
    function addScoreToLeaderboard(name, score, difficulty) {
        const leaderboardData = JSON.parse(localStorage.getItem(`leaderboard_${difficulty}`)) || [];
        
        // 添加新分数
        leaderboardData.push({ name, score });
        
        // 按分数排序（降序）
        leaderboardData.sort((a, b) => b.score - a.score);
        
        // 只保留前10名
        const topScores = leaderboardData.slice(0, 10);
        
        // 保存到本地存储
        localStorage.setItem(`leaderboard_${difficulty}`, JSON.stringify(topScores));
        
        // 更新当前显示的排行榜
        const activeDifficulty = document.querySelector('.leaderboard-tab.active').dataset.difficulty;
        updateLeaderboardDisplay(activeDifficulty);
    }
    
    // 辅助函数：使颜色变亮
    function lightenColor(color, percent) {
        const num = parseInt(color.replace('#', ''), 16);
        const amt = Math.round(2.55 * percent);
        const R = (num >> 16) + amt;
        const G = (num >> 8 & 0x00FF) + amt;
        const B = (num & 0x0000FF) + amt;
        
        return '#' + (
            0x1000000 +
            (R < 255 ? (R < 1 ? 0 : R) : 255) * 0x10000 +
            (G < 255 ? (G < 1 ? 0 : G) : 255) * 0x100 +
            (B < 255 ? (B < 1 ? 0 : B) : 255)
        ).toString(16).slice(1);
    }
    
    // 键盘控制
    document.addEventListener('keydown', (event) => {
        if (!gameStarted || gameOver) return;
        
        // 防止反向移动
        switch (event.key) {
            case 'ArrowUp':
                if (velocityY !== 1) {
                    nextVelocityX = 0;
                    nextVelocityY = -1;
                }
                break;
            case 'ArrowDown':
                if (velocityY !== -1) {
                    nextVelocityX = 0;
                    nextVelocityY = 1;
                }
                break;
            case 'ArrowLeft':
                if (velocityX !== 1) {
                    nextVelocityX = -1;
                    nextVelocityY = 0;
                }
                break;
            case 'ArrowRight':
                if (velocityX !== -1) {
                    nextVelocityX = 1;
                    nextVelocityY = 0;
                }
                break;
        }
    });
    
    // 开始/重新开始按钮
    startButton.addEventListener('click', () => {
        if (!gameStarted) {
            initGame();
            gameStarted = true;
            startButton.textContent = '游戏中...';
            
            // 如果是第一次开始游戏，设置初始方向
            if (velocityX === 0 && velocityY === 0) {
                nextVelocityX = 1;
                nextVelocityY = 0;
            }
            
            gameLoop();
        }
    });
    
    // 提交分数按钮
    submitScoreButton.addEventListener('click', () => {
        const playerName = playerNameInput.value.trim() || '匿名玩家';
        addScoreToLeaderboard(playerName, score, currentDifficulty);
        hideGameOverModal();
    });
    
    // 再玩一次按钮
    playAgainButton.addEventListener('click', () => {
        hideGameOverModal();
        initGame();
        gameStarted = true;
        startButton.textContent = '游戏中...';
        nextVelocityX = 1;
        nextVelocityY = 0;
        gameLoop();
    });
    
    // 初始绘制
    drawGame();
});